﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Tb.App.API.Applicaions.Command.DeepProcessing;
using Tb.App.Domain.Rabbit.DeepProcessing;
using Tb.App.ErrorCode;
using Tb.App.Infrastructure.Interfaces;

namespace Tb.App.API.Applications.CommandHandler.DeepProcessing
{
    /// <summary>
    /// 添加深加工企业信息--处理
    /// </summary>
    public class AddDeepProcessingCompanyCommandHandler : IRequestHandler<AddDeepProcessingCompanyCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<DeepProcessingCompany> deeprocessingCompanyRep;
        private readonly ILogger<AddDeepProcessingCompanyCommandHandler> logger;

        public AddDeepProcessingCompanyCommandHandler(IBaseRepository<DeepProcessingCompany> deeprocessingCompanyRep,ILogger<AddDeepProcessingCompanyCommandHandler> logger)
        {
            this.deeprocessingCompanyRep = deeprocessingCompanyRep;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(AddDeepProcessingCompanyCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var executionStrategy =  deeprocessingCompanyRep.DB.Database.CreateExecutionStrategy();
            await executionStrategy.ExecuteAsync(async () =>
           {
               using (var transaction = await deeprocessingCompanyRep.DB.Database.BeginTransactionAsync())
               {
                   try
                   {

                       var exists = await deeprocessingCompanyRep.GetAll().Where(x=>!x.IsDel&&x.Batch==request.Batch).ToListAsync();
                       exists.ForEach(o =>
                       {
                           o.IsDel = true;
                       });
                       await deeprocessingCompanyRep.UpdateRange(exists);

                       DeepProcessingCompany entity = new DeepProcessingCompany()
                       {
                           CompanyName = request.CompanyName,
                           LicenseNum = request.LicenseNum,
                           Batch = request.Batch
                       };
                       var res = await deeprocessingCompanyRep.AddAsync(entity);
                       if (res > 0)
                       {
                           result.Data = res;
                           result.Code = ApiEnum.添加成功;
                           result.Message = "添加深加工企业信息成功";
                       }
                       else
                       {
                           result.Code = ApiEnum.添加失败;
                           result.Message = "添加深加工企业信息失败";
                       }
                       await transaction.CommitAsync();
                   }
                   catch (Exception ex)
                   {
                       result.Code = ApiEnum.添加失败;
                       result.Message = "添加深加工企业信息异常";
                       logger.LogError("添加深加工企业信息异常=>" + ex.Message);
                       await transaction.RollbackAsync();
                       throw;
                   }
               }
           });
            return result;
        }

        }
    }

